package com.haven.webrobotserver.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haven.webrobotserver.domain.EndRunner;
import com.haven.webrobotserver.domain.EndRunnerTask;
import com.haven.webrobotserver.endRunner.EndRunnerStatic;
import com.haven.webrobotserver.service.EndRunnerService;
import com.haven.webrobotserver.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/endRunner")
@CrossOrigin("http://localhost:8080")
public class EndRunnerController {

    @Autowired
    private EndRunnerService endRunnerService;

    @GetMapping("/heartBeat")
    public JSONObject heartBeat(@RequestParam(name="ip") String ip){
        JSONObject result = new JSONObject();


        long l = System.currentTimeMillis();

        EndRunner e = new EndRunner();
        e.setIp(ip);
        e.setLastHeartBeatTime(l);

        /*增加新的endRunner*/
        EndRunnerStatic.getOnlineEndRunners().add(e);
        /*更新timestap*/
        for(EndRunner endRunner:EndRunnerStatic.getOnlineEndRunners()){
            if(endRunner.getIp().equals(e.getIp())){
                endRunner.setLastHeartBeatTime(e.getLastHeartBeatTime());
                break;
            }
        }

        /*遍历任务池取任务*/
        synchronized (this.getClass()){
            if(Task.tasks.size()<1){
                return null;
            }else{
                for(EndRunnerTask t: Task.tasks){
                    if(t!= null && t.getEndRunnerIp().equals(ip)){
                        result.put("task",t);
                        Task.tasks.remove(t);
                    }
                    break;
                }
            }
        }
        return result;
    }

    @GetMapping("/getAllOnlineEndRunners")
    public JSONObject getAllOnlineEndRunners(){
        JSONObject result = new JSONObject();
        Set<EndRunner> allOnlineEndRunners = endRunnerService.getAllOnlineEndRunners();

        String s = JSONObject.toJSONString(allOnlineEndRunners);
        JSONArray objects = JSONObject.parseArray(s);

        result.put("data",objects);
        result.put("status",200);
        return result;
    }
}
